package com.shiwaixiangcun.customer.ui.activity

import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView

import com.baidu.mobstat.SendStrategyEnum
import com.baidu.mobstat.StatService
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.ResponseEntity
import com.shiwaixiangcun.customer.module.mall.GoodDetailActivity
import com.shiwaixiangcun.customer.ui.IDetailView
import com.shiwaixiangcun.customer.ui.dialog.ShareDialog
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.SdCordUtil
import com.shiwaixiangcun.customer.utils.Utils
import com.shiwaixiangcun.customer.widget.ChangeLightImageView
import com.shiwaixiangcun.customer.widget.X5WebView
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient

/**
 * @author Administrator
 */
class DetailsActivity : BaseActivity(), View.OnClickListener, IDetailView {


    private var backLeft: ChangeLightImageView? = null
    private var ivShareRight: ImageView? = null
    private var webView: X5WebView? = null
    private var articleId: String? = null
    private val webUrl = StringBuilder()
    private val shareUrl = StringBuilder()
    private var detailTitle: String? = null
    private var tvPageName: TextView? = null
    private var tvTop: View? = null
    private var detailContent: String? = null
    private var shareImage: String? = null
    private var siteId: Int = 0
    private var myProgressBar: ProgressBar? = null

    //    /**
    //     * 清除Cookie
    //     *
    //     * @param context
    //     */
    //    private static void removeCookie(Context context) {
    //        CookieSyncManager.createInstance(context);
    //        CookieManager cookieManager = CookieManager.getInstance();
    //        cookieManager.removeAllCookie();
    //        CookieSyncManager.getInstance().sync();
    //    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)
        val res = resources

        siteId = AppSharePreferenceMgr.get(mContext, GlobalConfig.CURRENT_SITE_ID, 20) as Int
        val bmp = BitmapFactory.decodeResource(res, R.drawable.start_page)
        shareImage = SdCordUtil.saveMyBitmap("shareImage", bmp)
        //        百度统计
        StatService.setLogSenderDelayed(10)
        StatService.setSendLogStrategy(this, SendStrategyEnum.APP_START, 1, false)
        StatService.setSessionTimeOut(30)

        val intent = intent
        articleId = intent.getStringExtra("articleId")
        detailTitle = intent.getStringExtra("detailTitle")
        detailContent = intent.getStringExtra("detailContent")
        initData()
        initViewAndEvent()
    }


    /**
     * 初始化视图
     */
    private fun initViewAndEvent() {

        webView = findViewById(R.id.x5WebView)
        backLeft = findViewById(R.id.back_left)
        ivShareRight = findViewById(R.id.iv_share_right)
        tvTop = findViewById(R.id.tv_top)
        myProgressBar = findViewById(R.id.myProgressBar)
        tvPageName = findViewById(R.id.tv_page_name)
        tvPageName!!.ellipsize = TextUtils.TruncateAt.END
        tvPageName!!.setLines(1)
        ivShareRight!!.visibility = View.VISIBLE
        backLeft!!.setOnClickListener(this)
        ivShareRight!!.setOnClickListener(this)
        initWebView()
    }

    private fun initWebView() {
        webView!!.webChromeClient = MyWebChromeViewClient()
        webView!!.webViewClient = MyWebViewClient()
        webView!!.loadUrl(webUrl.toString())
        webView!!.setOnScrollChangeListener(object : X5WebView.OnScrollChangeListener {
            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {

            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {

            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {

            }

            override fun scrollDistance(distant: Float) {
                if (distant > 300) {
                    if (Utils.isNotEmpty(detailTitle)) {
                        tvPageName!!.text = detailTitle
                        tvTop!!.visibility = View.VISIBLE
                    }

                } else {
                    tvPageName!!.text = ""
                    tvTop!!.visibility = View.GONE
                }

            }
        })
    }

    private fun initData() {


        webUrl.append(GlobalApi.DOMAIN_PM).append("/mi/article/detailView.htm")
                .append("?articleId=")
                .append(articleId)
                .append("&siteId=")
                .append(siteId)
                .append("&app=true")
        shareUrl.append(GlobalApi.DOMAIN_PM)
                .append("/mi/article/detailView.htm")
                .append("?articleId=")
                .append(articleId)
                .append("&siteId=")
                .append(siteId)
        Log.e(BUG_TAG, webUrl.toString())

    }

    override fun onClick(view: View) {
        val id = view.id
        when (id) {
            R.id.back_left -> finish()
            R.id.iv_share_right -> showShare()
            else -> {
            }
        }
    }

    override fun setBgaAdpaterAndClickResult(result: ResponseEntity<*>) {

    }

    private fun showShare() {
        val shareDialog = ShareDialog()
        val bundle = Bundle()
        bundle.putString("title", detailTitle)
        bundle.putString("titleUrl", shareUrl.toString())
        bundle.putString("text", detailContent)
        bundle.putString("imageUrl", "http://resource.hxteb.com/group1/M00/00/26/rBKx5Vl4TMCAUPgUAAB6YxNdWvs030.png")
        bundle.putString("siteUrl", shareUrl.toString())
        shareDialog.arguments = bundle
        shareDialog.show(this.fragmentManager, "shareDialog")
    }

    override fun onDestroy() {
        if (webView != null) {
            webView!!.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            webView!!.clearHistory()

            (webView!!.parent as ViewGroup).removeView(webView)
            webView!!.destroy()
            webView = null
        }
        super.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        StatService.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        StatService.onPause(this)
    }

    private inner class MyWebChromeViewClient : WebChromeClient() {

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            if (newProgress == 100) {
                myProgressBar!!.visibility = View.GONE
            } else {
                if (View.INVISIBLE == myProgressBar!!.visibility) {
                    myProgressBar!!.visibility = View.VISIBLE
                }
                myProgressBar!!.progress = newProgress
            }
            super.onProgressChanged(view, newProgress)
        }

    }

    /**
     * 处理通知 ，请求事件
     */
    private inner class MyWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {

            judgeUrl(url, view)
            return true
        }
    }


    /**
     * 判断连接是不是商品
     */
    private fun judgeUrl(linkUrl: String?, view: WebView) {
        if (null == linkUrl) {
            return
        }
        val mallUrl = GlobalApi.getJudgeUrl
        if (linkUrl.contains(mallUrl)) {
            Log.e(BUG_TAG, "是商品")
            //将路径通过"/"分割出来
            val arr1 = linkUrl.split("[/]".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            val length = arr1.size
            //取最后一个字段
            val url = arr1[length - 1]
            val goodId = url.substring(0, url.length - 4)
            val bundle = Bundle()
            bundle.putInt("goodId", Integer.parseInt(goodId))
            val intent = Intent(mContext, GoodDetailActivity::class.java)
            intent.putExtras(bundle)
            startActivity(intent)

        } else {
            view.loadUrl(linkUrl)

        }
    }


}
